//
//  YMGridView.swift
//  YMSwiftUI
//
//  Created by anscen on 2022/3/10.
//

import SwiftUI

struct YMGridView: View {
    @State public  var group :String = ""
    @State private var listAdap :[GridItem] =  [GridItem(.adaptive(minimum: grid_width, maximum: grid_width + 15), spacing: 0, alignment: .center)]
    @State private var listData :[YMClassifyItem] = []
    var body: some View {
        ScrollView {
            LazyVGrid(columns: listAdap, spacing: 10){
                ForEach(listData, id: \.self){
                    item in
                    YMGridCell(item: item,group:group)
                }
            }
        }.onAppear {
            self.loadData()
        }.onDisappear {
            
        }
    }
    func loadData(){
        ApiMoya.request(target: .classify) { json in
            debugPrint(json)
            let classify = YMClassify.deserialize(from: json.rawString())
            if let list = classify?.male{
                self.listData = list
            }
        } failure: { error in
            
        }
    }
}

struct YMGridCell :View {
    @State var item :YMClassifyItem
    @State var group :String
    @State var width :CGFloat = grid_width
    var body: some View{
        VStack {
            NavigationLink.init {
                YMListView(group:group, name: item.name).navigationTitle(item.name)
            } label: {
                VStack(alignment: .center, spacing: 12) {
                    WebImage(url: URL(string: item.cover)).resizable().placeholder {
                        RoundedRectangle(cornerRadius:5).foregroundColor(.gray)
                    }.indicator(.activity).transition(.fade).cornerRadius(5).padding(EdgeInsets.init(top: 20, leading: 0, bottom: 0, trailing: 0)).fill(alignment: .center).frame(width: width, height: width * 1.5, alignment: .center)
                    Text("\(item.name)").foregroundColor(.black).padding(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0)).font(Font(UIFont.systemFont(ofSize: 17, weight: .medium))).lineLimit(1)
                }
            }
        }
    }
}
